
const postModel = require('../model/adminPostModel');
module.exports = {
  getPostsByPage(req, res) {
    console.log(req.body);
    let { pageIndex, pageSize } = req.body;
    postModel.getPostByPage(pageIndex, pageSize, (err, result) => {
      if (err) console.error(err);
      let resObj = {};
      if (result.length > 0) {
        resObj.code = 200;
        resObj.msg = '获取成功';
        resObj.data = result;
      } else {
        resObj.code = 401,
          resObj.msg = '获取失败'
      }
      res.send(resObj);
    })
  },
  getPostByFilter(req, res) {
    // console.log(req.body);
    let { categoryId, status, pageIndex, pageSize } = req.body;
    let offset = (pageIndex - 1) * pageSize;
    // 如果 categoryId 是  all 就没有条件进行查询
    let sql = `SELECT posts.id,title,posts.\`status\`,created,nickname,\`name\` 
    FROM posts 
    JOIN users ON posts.user_id=users.id
    JOIN categories ON posts.category_id=categories.id   `
    // 我们得在这里对sql语句进行拼接操作，判断有没有筛选条件，得到是否有where语句
    // 因为条件在获取总数的时候也要使用，把它暂时的保存起来
    let condition = '';
    if (categoryId != 'all' || status != 'all') {
      condition += ` where `;
    }
    if (categoryId != 'all') {
      condition += ` posts.category_id=${categoryId} `;
    }
    if (status != 'all') {
      if (categoryId != 'all') {
        condition += ' and ';
      }
      condition += ` posts.\`status\`='${status}' `;
    }
    // 不要忘了把条件加给sql语句
    sql += condition;

    sql += `  LIMIT ${offset},${pageSize}`;
    // console.log(sql);

    postModel.getPostsByFilter(sql, (err, result) => {
      console.log(result)
      if (err) console.error(err);
      let resObj = {};
      if (result.length > 0) {
        resObj.code = 200;
        resObj.msg = '获取成功';
        resObj.data = result;
        // 直接调用model里面的获取总条数的方法，获取总条数，计算出最大页码数
        postModel.getPostCount(condition, (err, result) => {
          
          if (err) console.error(err);
          if (result) {
            let maxPage = Math.ceil(result[0].total / pageSize);
            resObj.maxPage = maxPage;
            
          }
          res.send(resObj);
        })
      } else {
        resObj.code = 401,
          resObj.msg = '获取失败'
        res.send(resObj);
      }

    });
  },

  //处理封面图片的上传
  uploadImage(req, res) {
    // 创建一个用于解析post请求的对象
    let form = new formidabl.IncomingForm();
    // 先指定上传的目录
    form.uploadDir = __dirname + '/../uploads';
    // 让上传的文件保持后缀名
    form.keepExtensions = true;
    // 开始解析
    form.parse(req, (err, ziduan, wenjian) => {
      // err - 如果出错，就会在这里报错
      // console.log(err);
      // ziduan 就是传递回来的字段数据
      // console.log(ziduan);
      // wenjian 就是上传回来的文件
      // console.log(wenjian);
      let resObj = {
        code: 401,
        msg: '上传失败'
      };
      if (!err) {
        resObj.code = 200;
        resObj.msg = '上传成功';
        let index = wenjian.pic.path.indexOf('uploads');
        resObj.data = '/' + wenjian.pic.path.substring(index);
      }
      res.send(resObj);
    })
  },

  // 添加新的文章的接口
  addNewPost(req, res) {
    // console.log(req.body);
    // req.body里面是缺少一个用户的id的，我们是从登陆的session里面可以获取到一个用户的id，
    let user_id = req.session.userInfo.id;
    // console.log(user_id);
    // 把数据补充完整
    req.body.user_id = user_id;
    // 找model进行新增操作
    postModel.addNewPost(req.body, (err, result) => {
      if (err) console.error(err);
      let resObj = {
        code: 401,
        msg: '新增失败'
      };
      if (result.affectedRows == 1) {
        resObj.code = 200;
        resObj.msg = '新增成功';
      }
      res.send(resObj);
    })
  }
}